import React,{ Component } from 'react';
import {getInputChangeAction,getAddItemAction,getDelItemAction,getTodoList,getInitList} from '../store/actionCreators'
import store from '../store';
import TodoListUI from './TodoListUI';

class TodoList extends Component {
    constructor (props) {
        super(props);
        this.state=store.getState();

        this.handleInputChange=this.handleInputChange.bind(this);
        this.handleBtnClick=this.handleBtnClick.bind(this);
        this.handleItemClick=this.handleItemClick.bind(this);
        
        //store改变里面的函数就会执行
        this.handleStoreChange=this.handleStoreChange.bind(this);
        store.subscribe(this.handleStoreChange);
    }

    render(){
        return (
            <TodoListUI 
                inputValue={this.state.inputValue} 
                list={this.state.list} 
                handleInputChange={this.handleInputChange} 
                handleBtnClick={this.handleBtnClick} 
                handleItemClick={this.handleItemClick} 
            />
        )
    }

    //redux-thunk
    //在组件被挂载到页面后自动执行
    // componentDidMount(){
    //     const action = getTodoList();
    //     store.dispatch(action);
    // }

    componentDidMount(){
        const action=getInitList();
        store.dispatch(action);
    }

    handleInputChange(e){
        //修改store中的内容
        const action = getInputChangeAction(e.target.value);
        store.dispatch(action);
    }

    handleBtnClick(e){
        //修改store中的内容,插入列表
        const action = getAddItemAction(this.state.inputValue);
        store.dispatch(action);
    }

    handleItemClick(index){
        const action = getDelItemAction(index);
        store.dispatch(action);
    }

    handleStoreChange(){
        //改变state的数据
        this.setState(store.getState());
    }
}

export default TodoList;